import { UserManager, UserManagerSettings, WebStorageStateStore } from "oidc-client";

function createUserManager() {
    const host = window.location.host;
    const settings: UserManagerSettings = {
        authority: `http://${host}`,
        client_id: "ddck",
        client_secret: "secret",
        redirect_uri: `http://${host}/authentication/login-callback`,
        post_logout_redirect_uri: `http://${host}/authentication/logout-callback`,
        response_type: "code",
        scope: "modify control monitor openid profile offline_access",
        automaticSilentRenew: true,
        includeIdTokenInSilentRenew: true,
        userStore: new WebStorageStateStore({
            prefix: 'ddck'
        })
    }
    const userManager = new UserManager(settings);
    userManager.events.addUserSignedOut(async () => {
        await userManager.removeUser();
        console.warn("用户已登出，将重新登录")
    });
    userManager.events.addAccessTokenExpired(async () => {
        console.warn(`token过期，将重新登录，参数数量：${arguments.length}`)
    })
    userManager.events.addSilentRenewError(async () => {
        console.warn(`token刷新失败，将重新登录：${arguments.length}`)
    })
    userManager.events.addAccessTokenExpiring(async () => {
        console.warn(`token即将过期：${arguments.length}`)
    });
    userManager.events.addUserSignedIn(async () => {
        console.warn(`用户已登录：${arguments.length}`)
    });
    userManager.events.addUserUnloaded(async () => {
        console.warn(`用户已卸载：${arguments.length}`)
    });
    userManager.events.addUserLoaded(async () => {
        console.warn(`用户已加载：${arguments.length}`)
    });
    userManager.events.addUserSessionChanged(async () => {
        console.warn(`用户会话已更改：${arguments.length}`)
    });
    return userManager;
}
const userManager = createUserManager();
async function signIn() {
    await userManager.signinRedirect({ abc: 123 });
}
async function completeSignIn() {
    return await userManager.signinCallback(window.location.href);
}
async function getUser() {
    return userManager.getUser();
}
export default {
    signIn,
    completeSignIn,
    getUser
}

export const LoginActions = {
    Login: 'login',
    LoginCallback: 'login-callback',
    LoginFailed: 'login-failed',
};
